﻿using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentAgriculture.Domain.Impl
{
    public class ParturitionRepository : IParturitionRepository
    {
        private readonly AgricultureDbContext _context;
        public ParturitionRepository(AgricultureDbContext context)
        {
            _context = context;
        }
        /// <summary>
        /// 分娩列表
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<Childbirth>> GetChildbirth()
        {
            return _context.Childbirths.Where(c => c.Isdel == false).AsNoTracking();
        }
        /// <summary>
        /// 添加种母分娩
        /// </summary>
        /// <param name="sheeppregnancy"></param>
        /// <returns></returns>
        public async Task<int> AddChildbirth(List<Childbirth> childbirth)
        {
            _context.Childbirths.AddRange(childbirth);
            return await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 修改种母分娩信息
        /// </summary>
        /// <param name="childbirth"></param>
        /// <returns></returns>
        public async Task<int> UpdateChildbirth(Childbirth childbirth)
        {
            _context.Childbirths.Update(childbirth);
            return await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 种母分娩删除
        /// </summary>
        /// <param name="eartag"></param>
        /// <returns></returns>
        public async Task<int> DeleParturition(string? eartag)
        {
            //修改分娩
            var entity = _context.Childbirths.FirstOrDefault(c => c.EarTag == eartag);
            if (entity != null)
            {
                entity.Isdel = true;
            }
            _context.Childbirths.Update(entity);
            //修改妊检
            var pregnancy = _context.Sheeppregnancies.FirstOrDefault(c => c.EarTag == eartag);
            if (pregnancy != null)
            {
                pregnancy.IsDel = false;
            }
            _context.Sheeppregnancies.Update(pregnancy);
            //修改档案
            var sheepfile = _context.Sheepfilemodels.FirstOrDefault(c => c.EarTag == eartag);
            //根据档案耳号 获取分娩数据
            var childbirth =_context.Childbirths.FirstOrDefault(s=>s.EarTag ==sheepfile.EarTag);
            if (sheepfile != null)
            {
                sheepfile.BuildingId = childbirth.CurrentBuilding;
                sheepfile.ColumnId = childbirth.CurrentField;
                sheepfile.ReproductionState = 7;
            }
            _context.Sheepfilemodels.Update(sheepfile);
            return await _context.SaveChangesAsync();
        }
    }
}
